package model

import (
	"errors"
	"regexp"
	"time"
)

type Question struct {
	Id         int64 `json:"-"`
	Type       int32
	CreatedAt  time.Time `xorm:"created"`
	UpdatedAt  time.Time `xorm:"updated"`
	Stem       string    `xorm:"text"`
	Pic        string
	Answer     string `xorm:"text"`
	Explain    string `xorm:"text"`
	ExpPic     string
	Selections map[string]string
}

func (q *Question) Some(ids []int64) ([]*Question, error) {
	var questions []*Question
	err := orm.In("id", ids).Asc("id").Find(&questions)
	return questions, err
}

func (q *Question) OneById() error {
	ok, err := orm.ID(q.Id).Get(q)
	if !ok {
		return errors.New(QuestionNotFound)
	}
	return err
}

func (q *Question) StemLike(like string) ([]*Question, error) {
	var questions []*Question
	err := orm.Where("stem LIKE ?", "%"+like+"%").Find(&questions)
	return questions, err
}

func (q *Question) UpdateBy(col ...string) error {
	ok, err := orm.ID(q.Id).Cols(col...).Update(q)
	if ok == 0 {
		return errors.New(QuestionUpdateFailed)
	}
	return err
}

func (q *Question) Create() error {
	ok, err := orm.Insert(q)
	if ok == 0 {
		return errors.New(QuestionCreateFailed)
	}
	return err
}

func (q *Question) TrimSpace() error {
	re, err := regexp.Compile(`[ ]{2,5}`)
	if err != nil {
		return err
	}
	if !re.MatchString(q.Stem) {
		return nil
	}
	q.Stem = re.ReplaceAllString(q.Stem, "___")
	ok, err := orm.ID(q.Id).Cols("stem").Update(q)
	if ok == 0 {
		return errors.New(QuestionCreateFailed)
	}
	return err
}
